package middleware

import (
	"fmt"
	"gomain/app/service"
	"strings"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
)

// 动态权限验证中间件
func DynamicPermission(r *ghttp.Request) {
	ctx := r.GetCtx()

	if r.URL.Path == "/api/user/login" {
		g.Log().Debug(ctx, "跳过登录接口的权限检查")
		r.Middleware.Next()
		return
	}

	userId := r.GetCtxVar("user_id").Int()

	// 特殊处理：userId=1 拥有所有权限
	if userId == 1 {
		r.Middleware.Next()
		return
	}

	if userId == 0 {
		g.Log().Warning(ctx, "未获取到用户ID", "path", r.URL.Path)
		r.Response.WriteJson(g.Map{
			"code": 401,
			"msg":  "未登录",
		})
		r.Exit()
	}

	// 获取当前请求的路径和方法
	path := r.URL.Path
	method := strings.ToLower(r.Method)

	// 构造权限码
	permissionCode := fmt.Sprintf("%s:%s", method, strings.TrimPrefix(path, "/api/"))

	g.Log().Debug(ctx, "权限检查",
		"userId", userId,
		"path", path,
		"method", method,
		"permissionCode", permissionCode,
	)

	if !service.Permission.HasPermission(userId, permissionCode) {
		g.Log().Warning(ctx, "权限检查失败",
			"userId", userId,
			"permissionCode", permissionCode,
		)
		r.Response.WriteJson(g.Map{
			"code": 403,
			"msg":  "没有权限",
		})
		r.Exit()
	}

	g.Log().Debug(ctx, "权限检查通过", "userId", userId, "permissionCode", permissionCode)
	r.Middleware.Next()
}
